package com.demo.controller;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.demo.service.CourseServiceV4;
import com.demo.service.CourseServiceV5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: bj910
 * Date:2023-08-07
 * Time: 23:12
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/ds5")
public class CourseControllerV5 {

    @Autowired
    CourseServiceV5 courseService;

    @Resource
    DynamicRoutingDataSource dataSource;

    @ResponseBody
    @RequestMapping("/sessionTest")
    public Object queryCourse(@RequestParam(value = "key",defaultValue = "write") String key, HttpServletRequest request){
        request.getSession().setAttribute("rw",key);
        return courseService.selectCourse();
    }

    @ResponseBody
    @RequestMapping("/addDB")
    public Object addDB(){
        DruidDataSource dds = new DruidDataSource();
        dds.setUsername("root");
        dds.setPassword("root");
        dds.setUrl("jdbc:mysql://192.168.0.61:3306/shardingjdbc_3?serverTimezone=UTC&useSSL=false");
        dds.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.addDataSource("test",dds);
        return "DB added";
    }

    @ResponseBody
    @RequestMapping("/getDB")
    public Object getDB() throws SQLException {
//        DruidDataSource dds = new DruidDataSource();
//        dds.setUsername("root");
//        dds.setPassword("root");
//        dds.setUrl("jdbc:mysql://192.168.0.61:3306/shardingjdbc_3?serverTimezone=UTC&useSSL=false");
//        dds.setDriverClassName("com.mysql.cj.jdbc.Driver");
//        dataSource.addDataSource("test",dds);
        //既然 dataSource可以add 那么也可以get
        Map<String, DataSource> dataSources = dataSource.getDataSources();
        for (DataSource value : dataSources.values()) {
            Connection connection = value.getConnection();
        }
        return "getDB";
    }
}
